const express = require("express");
const router = express.Router();
const db = require("../models");
const verify = require("../tools/verifyToken");

router.get("/all", verify, (req, res) => {
  console.log(req.ip);
  db.Client.findAll().then((clients) => res.send(clients));
});

router.get("/get_by_id", verify, (req, res) => {
  db.Client.findOne({
    where: {
      id: req.query.id,
    },
  })
    .then((client) => {
      res.send(client);
    })
    .catch((err) => {
      res.status(400).send({ msg: err.message });
    });
});

router.get("/to_be_censored", verify, (req, res) => {
  // console.log('hi');
  // console.log(req.query);
  const checkerId = req.query.checkerId;
  const status = req.query.status;
  db.Client.findAll({
    where: {
      checker_id: checkerId,
      client_status: status,
    },
  })
    .then((clients) => {
      res.send(clients);
    })
    .catch((err) => {
      res.status(400).send({ msg: err.message });
    });
});

router.post("/censor", verify, async (req, res) => {
  const PASS = "通过";
  const data = req.body;
  const id = data.id;
  const checkerId = data.checker_id;
  const status = data.client_status;
  const checkSug = data.check_sug;
  try {
    const client = await db.Client.findOne({
      where: {
        id: id,
      },
    });
    if (!client) {
      throw new Error("没有此客户！");
    }
    if (client.checker_id != checkerId) {
      throw new Error("您没有权限审核客户");
    }
    if (client.client_status === PASS) {
      throw new Error("该客户已通过审核");
    }
  } catch (error) {
    res.status(400).send({ error: error.message });
  }
  db.Client.update(
    {
      client_status: status,
      check_sug: checkSug,
    },
    { where: { id: id } }
  )
    .then((success) => {
      res.send({ success });
    })
    .catch((err) => {
      res.status(400).send({ error: err.message });
    });
});

router.post("/add", verify, (req, res) => {
  const client = req.body;
  console.log(client);
  // if(!client.id)
  //     client.id = Math.floor(Math.random()*1000000+1)
  db.Client.create(client)
    .then((client) => {
      res.send(client);
    })
    .catch((err) => {
      res.status(400).send(err);
    });
});

router.post("/delete", verify, (req, res) => {
  db.Client.destroy({
    where: {
      id: req.body.id,
    },
  })
    .then(() => {
      res.send({ msg: "删除成功！" });
    })
    .catch((err) => {
      res.send(err);
    });
});

router.post("/edit", verify, (req, res) => {
  db.Client.update(req.body, {
    where: {
      id: req.body.id,
    },
  })
    .then(() => {
      res.send("done!");
    })
    .catch((err) => {
      res.send(err);
    });
});
module.exports = router;
